package plan;

public class Plan implements Comparable<Plan> {

	String strRoute = null;
	DistanceMatrix hD = null;
	int nDistance = 0;
	
	public Plan(String route, DistanceMatrix d){
		strRoute = route;
		hD = d;
		nDistance = d.getDistance(route);
	}
	
	@Override
	public int compareTo(Plan p) {
		if(p.nDistance > nDistance)
			return -1;
		else if(p.nDistance < nDistance)
			return 1;
		return 0;
	}
	
	@Override
	public String toString(){
		return strRoute;
	}
	
	public int getDistance(){
		return nDistance;
	}
	
	
	@Override
	public boolean equals(Object o){
		if(Plan.class.isInstance(o)){
			Plan p = (Plan)o;
			String pReverse = new StringBuffer(p.strRoute).reverse().toString();
			if(nDistance != p.nDistance)
				return false;
			if(strRoute.equals(p.strRoute))
				return true;
			else if(strRoute.equals(pReverse))
				return true;
			for(int i = 1; i<strRoute.length()-1;i++){
				if(strRoute.equals(p.strRoute.substring(i)+p.strRoute.substring(0, i))){
					return true;
				}
				else if(strRoute.equals(pReverse.substring(i)+pReverse.substring(0, i))){
					return true;
				}
			}
		}
		return false;
	}
	
	public static Plan createChild(Plan f, Plan m){
		String s1 = "";
		String s2 = f.toString().substring(4, 14);
		String s3 = "";
		for(int i = 0; i < 4; i++){
			for(int j = 0; j < m.toString().length();j++){
				String s = m.toString().substring(j, j+1);
				if(s2.indexOf(s) == -1 && s1.indexOf(s) == -1){
					s1 += m.toString().substring(j, j+1);
					break;
				}
			}
		}
		
		for(int i = 0; i < 4; i++){
			for(int j = 0; j < m.toString().length();j++){
				String s = m.toString().substring(j, j+1);
				if(s2.indexOf(s) == -1 && s1.indexOf(s) == -1 && s3.indexOf(s) == -1){
					s3 += m.toString().substring(j, j+1);
					break;
				}
			}
		}
		Plan p = new Plan(s1+s2+s3, m.hD);
		return p;
	}
	
	public void mutate(int nTimes){
		int n,m;
		for(int i = 0; i<nTimes;i++){
			n = (int) (Math.random()*strRoute.length());
			m = (int) (Math.random()*strRoute.length());
			strRoute = swapPositions(strRoute, n,m);
		}
		nDistance = hD.getDistance(strRoute);
	}
	
	private String swapPositions(String s, int i, int j){
		if(i == j)
			return s;
		int first = Math.min(i, j);
		int last = Math.max(i, j);
		char temp1 = s.charAt(first);
		char temp2 = s.charAt(last);
		
		String s1 = s.substring(0, first);
		String s2 = s.substring(first+1, last);
		String s3 = s.substring(last+1);
		
		return s1+temp2+s2+temp1+s3;
		
	}
	
}
